<?php

namespace app\api\controller\v1;

use addons\third\library\Service;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\Bill;
use app\common\model\Earnings;
use app\common\model\MemberMoney;
use app\common\model\User;
use app\common\model\WishList;
use app\common\model\WishListMoney;
use app\common\model\WishOrder;
use app\common\model\Withdrawal;
use Endroid\QrCode\QrCode;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\Response;
use app\common\model\Member as MemberModel;
class Member extends Api
{

    protected $allowFields=['*'];
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    /**
     * 生成我的二维码
     * @return Response
     * @throws \Endroid\QrCode\Exceptions\DataDoesntExistsException
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
     */

    public function myCode()
    {
        $mycode=new QrCode();
        $mycode->setText('http://www.baidu.com');
        $mycode->setLogo(ROOT_PATH.'public/assets/img/logo.png');
        $mycode->setSize(250);
        $mycode->setErrorCorrection('medium');
        $this->success('',$mycode->getDataUri());
    }

    /**
     * 登录
     * @return bool
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $params = $this->request->request();
        $params['platform'] = 'wechat';
//        $params['createtime']=time();
        $auth = Auth::instance();
        $member = MemberModel::get(['openid' => $params['openid']]);
        if ($member) {
            $user = User::get($member['member_id']);
            if (!$user) {
                return false;
            }
           $auth->direct($user->id);
            $this->success('登录成功',$auth->getToken());
        } else {
            // 先随机一个用户名,随后再变更为u+数字id
            $username = Random::alnum(20);
            $password = Random::alnum(6);
            $domain = request()->host();

            Db::startTrans();

            // 默认注册一个会员
            $result = $auth->register($username, $password, $username . '@' . $domain, '');
            if (!$result) {
                return false;
            }
            $user = $auth->getUser();

            $fields = ['username' => 'u' . $user->id, 'email' => 'u' . $user->id . '@' . $domain];

            if (isset($params['userinfo']['nickname'])) {
                $fields['nickname'] = $params['userinfo']['nickname'];
            }
            if (isset($params['userinfo']['avatar'])) {
                $fields['avatar'] = htmlspecialchars(strip_tags($params['userinfo']['avatar']));
            }

            // 更新会员资料
            $user = User::get($user->id);
            $user->save($fields);

            // 保存第三方信息
            $params['member_id'] = $user->id;
            $params['createtime']=time();
            unset($params['s']);
            if(MemberModel::create($params)){
                Db::commit();
                $auth->direct($user->id);
                $this->success('登录成功',$auth->getToken());
            }else{
                Db::rollback();
                $this->error('登录异常');
            }



        }
    }

    /**
     * 个人信息
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function MemberInfo()
    {

        $member_id=$this->auth->id;
        $member_id=4;
        $inviter=MemberModel::get($member_id,'inviter');
        $membermoney=MemberMoney::get(['member_id'=>$member_id]);
        $drawmoney=$membermoney['money'] ;
        $earnings=$membermoney['earnings'];
        $groupmoney=MemberModel::where(['id'=>$member_id])->with(['groupMoney'])->find();
        if($groupmoney['group_money']){
            $ids=array_column($groupmoney['group_money'],'id');
        }else{
            $ids=NULL;
        }
        $grandson =MemberModel::where('pid','in',$ids)->select();
        if($ids){
            $ids=array_merge(array_column($grandson,'id'),$ids);
        }else{
            $ids=$ids;
        }

        $data=[
            'item'=>$inviter,
            'drawmoney'=>$drawmoney,
            'earnings'=>$earnings,
            'groupmoney'=>MemberMoney::where('member_id','in',$ids)
//                ->field('earnings')
                ->select(),
            'money'=>WishListMoney::where('member_id',$member_id)->sum('money')
        ];
        $this->success('',$data);

    }


    /**
     * 我的团队
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myTeam()
    {
        $member_id=$this->auth->id;
        $member_id=16;
        $first_stage=MemberModel::get(['member_id'=>$member_id],'groupMoney.money');

        if($first_stage['group_money']){
         $children= MemberModel::where('member_id','in',array_column($first_stage['group_money'],'id'))->select();
//            halt($children);
         $grandson= MemberModel::where('pid','in',array_column($children,'id'))->select();

         $cearnings=Earnings::where('member_id','in',array_column($children,'id'))->whereTime('createtime','year')->sum('earnings');
         $grandson= MemberMoney::where('member_id','in',array_column($grandson,'id'))->select();
         $gearnings=Earnings::where('member_id','in',array_column($grandson,'id'))->whereTime('createtime','year')->sum('earnings');
//         halt($children);
         $data=[
           'item'=>$first_stage,
           'cearnings'=>$cearnings,
           'grandson'=>$grandson,
           'gearnings'=>$gearnings,
            'group_num'=>MemberModel::where('pid','in',array_column($children,'id'))->count(1)
         ];
         $this->success('',$data);
        }

       $this->error('');
    }

    /**
     * 查看直属
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function underling($status=10)
    {
        $member_id=$this->request->request('member_id');
//        $member_id=3;
        $member=MemberModel::with(['money'=>function($query){
            return $query->field('member_id,earnings');
        }])->where(['member_id'=>$member_id])->find();
//        halt($member);
       $wish=  new Wish();

        switch ($status){
            case 20;
                $data=WishList::where(['member_id'=>$member_id,'status'=>10])->find();
                $total['total']=WishListMoney::where(['wish_list_id'=>$data['id']])->sum('money');
                $this->success('',['member'=>$member,'item'=>$data,'total'=>$total]);
                ;break;
            case 30;
//            if(!WishList::where(['member_id'=>$member_id,'status'=>30])->count(1)>0)
//                $this->error('Not fulfilling one\'s wish');
                $data=WishList::where(['member_id'=>$member_id,'status'=>$status])
                    ->select()->each(function ($e){
                        return $e['total']=WishListMoney::where(['wish_list_id'=>$e['id']])->sum('money');
                    });
                $this->success('',['member'=>$member,'item'=>$data]);
                ;break;
            default:
                $queue=$wish->rank($member_id);
                $data=WishList::where(['member_id'=>$member_id,'status'=>$status])->find();
                $this->success('',['member'=>$member,'item'=>$data,'queue'=>$queue]);
        }
    }

    /**
     * @param int $type
     * @param int $page
     * @throws \think\exception\DbException
     */
    public function bill($type=1,$page=1)
    {
        $member_id=$this->auth->id;
        $member_id=1;
        if($type==1){
            $data=Bill::where(['member_id'=>$member_id])->order('createtime','desc')->paginate(20,false,['page'=>$page]);

            foreach ($data as &$item){
                $item['createtime']=date('Y-m-d H:i',$item['createtime']);
                switch ($item['type']){
                    case 10;
                        $item['type']='心愿完成';break;
                    case 20;
                        $item['type']='直属好友完成心愿'; break;
                    case 30;
                        $item['type']='间接好友完成心愿';break;
                }
            }
            $this->success('',$data);
        }else{
            $data['withdraw']=Withdrawal::where(['member_id'=>$member_id,'status'=>10])->order('createtime','desc')
                ->paginate(10,false,['page'=>$page]);
            foreach ($data['withdraw'] as &$list){
                $list['updatetime']=date('Y-m-d H:i',$list['updatetime']);

            }
            $data['top_up']=WishOrder::where(['member_id'=>$member_id,'status'=>10])->order('createtime','desc')->paginate(10,false,['page'=>$page]);
            foreach ($data['top_up'] as &$list){
                $list['updatetime']=date('Y-m-d H:i');
            }
            $this->success('',$data);
        }


    }

    /**
     * 提现
     */
     public function withdraw()
     {
        $member_id=$this->auth->id;
//        $member_id=1;
        $money=$this->request->post('money');
        if(empty($money)||$money==0){
            $this->error('提现金额不能为空');
        }
       $memberMoney= MemberMoney::where(['member_id'=>$member_id])->value('money');
        if($money>$memberMoney){
            $this->error("最高提现金额为{$memberMoney}");
        }
         $withdrawal = new Withdrawal();
         $withdrawal->money = $money;
         $withdrawal->member_id=$member_id;
         $withdrawal->createtime=time();

         if($withdrawal->save()){
            $m= Db::name('member_moeny')->where('member_id',$member_id)->value('money');
            Db::name('member_money')->where('member_id',$member_id)->update([
                'money'=>$m-$money
            ]);
             $this->success('提交成功，小二正在快马加鞭审核');
         }else{
             $this->error('提交失败,请稍后再试');
         }
     }


}
